<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use app\index\model\Inquiry as InquiryModel;
use app\admin\model\Repertory as RepertoryModel;

class Inquiry extends Controller
{

    private $inquiry;
    private $repertory;

    function initialize()
    {
        parent::initialize();
        $this->inquiry = new InquiryModel();
        $this->repertory = new RepertoryModel();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return view();
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {

        // 1、接收数据
        $param = input('post.');

        // 2、拼接数据
        $param['capital_money'] = str_replace(',', '', $param['capital_money']);
        $param['ask_time'] = time();
        $param['user_id'] = 1;
        if (!empty($param['oneMonth'])) {
            $param['oneMonth'] = 0;
        }
        if (!empty($param['twoMonth'])) {
            $param['twoMonth'] = 0;
        }
        if (!empty($param['threeMonth'])) {
            $param['threeMonth'] = 0;
        }

        // 3、插入数据
        $result = $this->inquiry->save($param);
        if ($result) {
            $this->success('以发送询价,请等待回执');
        }
        $this->error('发送询价失败!');

    }

    /**
     * 显示指定的资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //

    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        // 模糊查询仓
        $repertories = db('repertory')
            ->where('code', 'like', '%' . $id . '%')
            ->limit(3)
            ->select();

        return $repertories;
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * 查看所有的佚回执的消息
     */
    function messages() {

        // 当前用户已被回执的所有消息
        $messages = InquiryModel::where(['status' => 2, 'user_id' => 1])->select();

        // 修改询价时间格式
        foreach ($messages as $v) {
            $v['ask_time'] = date('Y-m-d H:i:s');
            $repertoryName = RepertoryModel::where('id', $v['reper_id'])->value('name');
            $v['reper_name'] = $repertoryName;
        }

        $this->assign('messages', $messages);
        return view();
    }

}
